package com.chuan.thinkingjava.interview.jdk8.stream;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class TestStream {

    public static void main(String[] args) {

        List<String> nameList = new ArrayList<>();
        nameList.add("张三");
        nameList.add("李四");
        nameList.add("王五");
        nameList.add("赵六");
        nameList.add("田七");
        nameList.add("王八");
        nameList.add("张四");
        nameList.add("张三丰");

        //传统的筛选过滤
        List<String> result = new LinkedList<>();
        for (String str: nameList) {
            if (str.startsWith("张") && str.length() == 2)
                result.add(str);
        }
        System.out.println(result);

        //jdk8
        List<String> result1 = nameList.stream().filter(s -> s.startsWith("张"))
                .filter(s -> s.length() == 2)
                .collect(Collectors.toList());
        System.out.println(result1);

        //stream object
        List<Person> lists = new LinkedList<>();
        for (int i = 0; i < 5; i++) {
            Person person = new Person();
            person.setId(i + 1);
            person.setName("张三" + i);
        }

        Collection<Person> collect = lists.stream().limit(2).sorted((p1, p2) -> p1.getName().compareTo(p2.getName())).collect(Collectors.toList());
        System.out.println(collect);
    }

    static class Person {
        private int id;

        private String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
